import base64 from "./base64.min"
import API from "../plugins/api"
import { config } from "../config"

let globalData = {}
const app = getApp()

export function againLogin() {
	// wx.showLoading({ mask: true, title: "登录中~" })
	wx.login({
		success: (res) => {
			const request = { code: res.code, loginType: 1 }
			console.log("访问登录接口", request)
			API["login/login"](request)
				.then((result) => {
					const { token, data, schoolConfig } = result
					// this.storageData(token, data[0], schoolConfig)
					wx.setStorage({ key: "token", data: token })
					wx.setStorage({ key: "userInfo", data: data[0] })
					wx.setStorage({ key: "schoolConfig", data: schoolConfig })
					globalData.userId = wx.getStorageSync("userInfo").userId
					wx.setStorage({ key: "code", data: res.code })
					// wx.hideLoading()

					if (app.afterLoginCallbackList && app.afterLoginCallbackList.length > 0) {
						console.log("登录之后钩子")
						app.afterLoginCallbackList.forEach((item) => {
							item()
						})
						app.afterLoginCallbackList = []
					} else {
						if (!globalData.redirect && bool) {
							globalData.enterPage = ""
							wx.reLaunch({
								url: "/pages/home/index",
							})
						}
					}
				})
				.catch((err) => {
					// wx.hideLoading()
					if (!globalData.isHzdb) {
						if (err === "-3001" && globalData.enterPath !== config.loginPage) {
							console.log("用户没有绑定过微信")
							// 用户没有绑定过微信
							wx.reLaunch({
								url: config.loginPage,
							})
						} else {
							// 后端改状态麻烦,这里改判断汉字,如果报错,请第一时间排除此处
							if (err === "该学校暂未开放") {
								wx.showModal({
									title: "提示",
									content: err,
									showCancel: false,
									complete: (msg) => {
										wx.reLaunch({
											url: config.loginPage,
										})
									},
								})
							}
							console.log("login/checkLogin", err)
						}
					}
				})
		},
		fail: (err) => {
			// wx.hideLoading()
			wx.showModal({
				title: "提示",
				content: "获取code失败,请退出微信后重试",
				showCancel: false,
			})
		},
	})
}

export function loginVerify(enterPage = "") {
	const token = wx.getStorageSync("token")
	if (token) {
		//校验token是否已经过期
		try {
			const tokenPlyload = base64.decode(token.split(".")[1])
			const tokenJson = JSON.parse(tokenPlyload)
			const currentTime = new Date().getTime()
			let { exp } = tokenJson
			exp = parseInt(exp + "000")
			if (exp - currentTime > 60 * 1000 * 50) {
				// if (exp - currentTime > 86400000 * 5) {
				// 86400000 * 5
				// token未过期（86400000为1天的时间戳，这个判断为每两天一刷）
				globalData.userId = wx.getStorageSync("userInfo").userId
				globalData.enterPage === enterPage, wx.hideLoading()
			} else {
				console.log("token已过期")
				// token已过期
				wx.setStorage({ key: "token", data: "" })
				againLogin()
			}
		} catch (error) {
			wx.hideLoading()
			wx.showModal({
				title: "提示",
				content: "登录异常",
				showCancel: false,
			})
			wx.clearStorageSync()
			console.log("token错误", error, token)
		}
	} else {
		againLogin()
	}
}
export default {
	loginVerify,
	againLogin,
}
